package com.wzu.springbootcrud2.realm;

import com.wzu.springbootcrud2.dao.UserMapper;
import com.wzu.springbootcrud2.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;


public class CustomerDBRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("授权调用。。。。。。。。。。。");
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("调用授权验证: "+primaryPrincipal);
        User user = userMapper.selectByUsercode(primaryPrincipal);
        System.out.println("user:"+user);
        //授权角色信息
        if(user.getUserrole()!=null){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole(user.getUserrole().toString()); //添加角色信息
            return simpleAuthorizationInfo;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("================================");
        //根据身份信息//从传过来的token获取到的用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        //根据身份信息查询
        User user = userMapper.selectByUsercode(principal);
        System.out.println("User:"+user.getUserpassword());
        //用户不为空
        if(!ObjectUtils.isEmpty(user)){
            //返回数据库信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                    user.getUsercode(),
                    user.getUserpassword(),
                    ByteSource.Util.bytes(user.getSalt()),
                    this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
